#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


import maya.cmds as cmds
import collections
import os
import yaml

class VerBakeAnimation(object):
    def __init__(self, config='bake_config.yml'):
        """
        baker = VerBakeAnimation(config='bake_config.yml')
        baker.bakeObjects = nodesList
        baker.frameRange = (1,100)
        baker.main()
        """
        self._config = config
        self.bakeObjects = None
        self._frameRange = None
        self._options = {}
        
    def _initData(self):
        configFile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', self._config)
        #configFile = 'D:/apps/verexport/config/bake_config.yml'
        if not os.path.isfile(configFile):
            raise RuntimeError("config file not exists: %s \n" % configFile)
        data = self.getConfigData(configFile)
        optionsData = data.get('options', None)
        if not optionsData:
            raise RuntimeError("config error.")
        self._options = optionsData
        
    @staticmethod
    def getConfigData(configFile):
        data = None
        with open(configFile) as f:
            data = yaml.load(f)
        if data:
            return data
        else:
            raise RuntimeError("load config data is none.")

    @property
    def frameRange(self):
        return self._frameRange

    @frameRange.setter
    def frameRange(self, value):
        if isinstance(value, collections.Iterable):
            self._frameRange = list(value)
        else:
            raise TypeError("Value should be an iterable.")
            
    def main(self):
        self._initData()
        if not self.bakeObjects:
            raise RuntimeError("Please set exportObjects.")
        if not self._frameRange:
            self._frameRange = (cmds.playbackOptions(q=1, ast=1), cmds.playbackOptions(q=1, aet=1))
        cmds.bakeResults(self.bakeObjects, time=tuple(self._frameRange), **self._options)

    